<template>
    <div class="pc-messages-wrap">
        <a-row type="flex">
            <a-col :flex="1">
                <a-popover v-model="popVisible" :getPopupContainer="(triggerNode) => triggerNode.parentNode" trigger="click">
                    <template slot="content">
                        <div v-if="searchContacts.length>0">
                            <div class="serach-item small-hand" @click="handleChoosePeople(item),popVisible=false" v-for="item in searchContacts" :key="item.id">
                                <div class="avatar">
                                    <img :src="item.peopleAvatar" alt="">
                                </div>
                                <div class="name">{{ item.peopleName }}</div>
                            </div>
                        </div>
                        <div v-else>
                            <a-empty />
                        </div>
                    </template>
                    <a-input-search v-model="searchName" placeholder="搜索联系人" style="width: 100%" @change="searchPeople" />
                </a-popover>
                <div class="messages">
                    <a-collapse default-active-key="2" :bordered="false">
                        <!-- <a-collapse-panel key="1" header="最近联系">
                            <div class="people" :class="chooseItem.receive_id===item.receive_id || chooseItem.pub_id===item.pub_id ? 'active':''" @click="handleChoosePeople(item)" v-for="item in lastContacts" :key="item.id">
                                <div class="avatar-num">
                                    <div class="message-num">{{ item.unRead }}</div>
                                    <div class="avatar">
                                        <img :src="item.pub_id===userId ? item.receive_avatar:item.pub_avatar" alt="">
                                    </div>
                                </div>
                                
                                <div class="last-message">
                                    <div class="name">
                                        {{item.pub_id===userId ? item.receive_name:item.pub_name}}
                                    </div>
                                    <div class="content">
                                        {{item.content}}
                                    </div>
                                </div>
                            </div>
                        </a-collapse-panel> -->
                        <a-collapse-panel key="2" header="我的聊天" :disabled="false">
                            <div class="small-hand people" :class="chooseItem.peopleId===item.peopleId ? 'active':''"  @click="handleChoosePeople(item)" v-for="item in contacts" :key="item.id">
                                <div class="avatar-num">
                                    <div class="message-num" >{{ item.unRead }}</div>
                                    <div class="avatar">
                                        <img :src="item.peopleAvatar" alt="">
                                    </div>
                                </div>
                                
                                <div class="last-message">
                                    <div class="name">
                                        {{item.peopleName}}
                                    </div>
                                    <div class="content">
                                        {{item.lastContent}}
                                    </div>
                                </div>
                            </div>
                        </a-collapse-panel>
                    </a-collapse>
                </div>
            </a-col>
            <a-col :flex="3">
                <div v-if="chooseItem.peopleId" class="chat-room">
                    <div class="top" id="chat-top">
                        <div class="item" v-for="item in chatMessages" :key="item.id">
                            <div class="item-top" :class="item.pub_id===userId ? 'is-my-item-top' : ''">
                                <img :src="item.pub_avatar" alt="">
                                <div class="time">{{item.time}}</div>
                            </div>
                            <div class="item-bottom-wrap" :class="item.pub_id===userId ? 'is-my-item-bottom-wrap' : ''">
                                <div class="item-bottom">
                                    {{item.content}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="bottom">
                        <a-textarea v-model="sendContent" placeholder="请输入" :rows="4" />
                        <div class="btn">
                            <a-button @click="handleSendMessage" type="primary">
                            发送
                            </a-button>
                        </div>
                    </div>
                </div>
                <div v-else class="flex-center">
                    <a-empty></a-empty>
                </div>
            </a-col>
        </a-row>
    </div>
  </template>
  
  <script>
  import { getContacts ,searchContacts,showHistoryMessage,updateUnread,insertChat} from "@/api/request";
  import {getCurrentTime} from "@/assets/js/getTime"
//   import io from 'socket.io-client'
//     const socket = io('http://localhost:3007',{
//         path:'/socket'
//     })
  export default {
    name: 'pcMessages',
    components: {
      
    },
    data(){
        return{
            popVisible:false,
            contacts:[],
            // lastContacts:[],
            searchName:'',
            searchContacts:[],
            chooseItem:{},
            // choosePeopleId:"",
            chatMessages:[],
            userId:JSON.parse(localStorage.getItem('userInfo')).userId,
            sendContent:'',
            socket: null,               // Socket.IO 实例
            userInfo:JSON.parse(localStorage.getItem('userInfo'))
        }
    },
    sockets: {
        connect() {
            console.log('Connected to server');
        },
        messageReceived(message) {
            // console.log(message,'客户端接收返回的数据')
            //判断目的地是否是自己，不是直接不管
            //是自己的话，接着判断发送方是不是choosePeopleId
            //是的话，直接在数据库中新增一条，然后重新获取聊天记录
            //不是的话，在数据库中新增一条，同时unread++
            //这种方式就必须保证所有用户都在线才能接收到
            //得把对数据库的操作放在后端，前端监听到有数据进来，
            //只需要再获取一遍数据就好了

            if(message.receive_id===this.userId){
                if(this.chooseItem.peopleId===message.pub_id){
                    //获取历史消息
                    this.handleShowHistoryMessage()
                    //更新未读消息
                    this.handleUpdateUnread()
                    
                    // this.handleInsertChat(message)
                }else{
                    //获取联系人（里面有最新的未读消息）
                    // this.handleGetContacts()
                    // this.handleInsertChat(message)
                    // this.handleUpdateUnread(this.chooseItem.unRead++)
                }    
            }
            if(message.receive_id===this.userId || message.pub_id===this.userId){
                this.handleGetContacts()
            }
            
        },
    },
    methods:{
        searchPeople(){
            searchContacts({
                "peopleName":this.searchName
            }).then(res=>{
                if(res.data.status===0){
                    this.searchContacts=res.data.data
                    // console.log(this.searchContacts)
                }
            })
        },
        handleGetContacts(){
            getContacts().then(res=>{
                if(res.data.status===0){
                    this.contacts=res.data.data
                }
            })
        },
        async handleChoosePeople(item){
            this.chooseItem=item
            // console.log('选中',item)

            await this.handleShowHistoryMessage()
            //更新unread字段
            this.handleUpdateUnread()

            
            let element = document.getElementById("chat-top");
            element.scrollTop = element.scrollHeight;
        },
        async handleShowHistoryMessage(){
            await showHistoryMessage({
                "peopleId":this.chooseItem.peopleId
            }).then(res=>{
                if(res.data.status===0){
                    this.chatMessages=res.data.data
                }
            })
        },
        // handleGetLastContacts(){
        //     getLastContacts().then(res=>{
        //         if(res.data.status===0){
        //             this.lastContacts=res.data.data
        //             // console.log(res.data.data,'11')
        //         }
        //     })
        // },
        handleUpdateUnread(num=0){
            updateUnread({
                "unRead":num,
                "peopleId":this.chooseItem.peopleId
            }).then(res=>{
                if(res.data.status===0){

                }else{
                    this.$message.error(res.data.message)
                }
            })
        },
        handleInsertChat(message){
            insertChat(message).then(res=>{
                if(res.data.status==0){
                    // this.$message.success('发送成功！')
                }else{
                    this.$message.error(res.data.message)
                }
            })
        },
        handleSendMessage(){
            if(!this.sendContent){
                this.$message.error('发送的内容不能为空！')
                return
            }
            const message = {
                "pub_id":this.userInfo.userId,
                "pub_avatar":this.userInfo.avatar,
                "pub_name":this.userInfo.name,
                "receive_id": this.chooseItem.peopleId,
                "receive_avatar":this.chooseItem.peopleAvatar,
                "receive_name":this.chooseItem.peopleName,
                "content": this.sendContent,
                "time":getCurrentTime()
            };
            // 发送消息给socket
            this.$socket.emit('message', message);
            //在数据库中也要新增一条记录，unread不变
            // this.handleInsertChat(message)
            this.handleShowHistoryMessage()
            this.$message.success('发送成功！')
            this.sendContent=''
        }
    },
    beforeDestroy() {
        this.$socket.disconnect();
    },
    mounted(){
        //建立连接
        this.$socket.connect();
        this.handleGetContacts()
        // this.handleGetLastContacts()
        //这里一上来需要用空的关键词去搜索一次
        this.searchPeople()
    }
  }
  </script>
  
  <style scoped lang="less">
  .flex-center{
    height: 100%;
  }
  .active{
    background-color: rgb(185, 185, 185);
    border-radius: 5px;
  }
  .serach-item:last-of-type{
    margin-bottom: 0;
  }
  .serach-item{
    display: flex;
    align-items: center;
    margin-bottom:10px;
    .avatar{
        width: 45px;
        height: 45px;
        border-radius: 50%;
        overflow: hidden;
        img{
            width: 100%;
            height: 100%;
        }
    }
    .name{
        margin-left: 20px;
    }
  }
  .pc-messages-wrap{
    height: calc( 100vh - 77px );
    background-color: #f7f7d2e7;
    border-radius: 5px;
    padding: 10px;
    /deep/ .ant-row-flex{
        height: 100%!important;
    }
    .messages{
        margin-top: 10px;
        
        .people:last-of-type{
            margin-bottom: 0;
        }
        .people{
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            padding: 5px 2px;
            .avatar-num{
                position: relative;
                .message-num{
                    position: absolute;
                    right: 0;
                    top:0;
                    width: 15px;
                    height: 15px;
                    border-radius: 50%;
                    background-color: red;
                    color: white;
                    font-size: 12px;
                    line-height: 15px;
                    text-align: center;
                }
                .avatar{
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                    overflow: hidden;
                    img{
                        width: 100%;
                        height: 100%;
                    }
                }
            }
            .last-message{
                margin-left: 20px;
                .name{
                    font-weight: 600;
                }
                .content{
                    font-size: 12px;
                    color: grey;
                }
            }
        }
    }
    .chat-room{
        padding-left: 20px;
        .top{
            width: 100%;
            height: calc( 100vh - 233px );
            overflow: auto;
            .item{
                margin-bottom: 20px;
                .item-top{

                    display: flex;
                    align-items: center;
                    justify-content: left;
                    margin-bottom: 5px;
                    img{
                        display: inline-block;
                        width: 30px!important;
                        height: 30px!important;
                        border-radius: 50%;
                        margin-right: 5px;
                    }
                }
                .is-my-item-top{
                    justify-content:right;
                }
                .item-bottom-wrap{
                    display: flex;
                    justify-content: right;
                }
                .is-my-item-bottom-wrap{
                    justify-content: left;
                }
                .item-bottom{
                    width: 95%;
                    background-color: wheat;
                    border-radius: 10px;
                    padding: 5px;
                }
            }
        }
        .bottom{
            .btn{
                margin-top: 10px;
                text-align: right;
            }
        }
    }
  }
  </style>
  